<template>
  <el-form :inline="true" :model="query" class="demo-form-inline" style="margin-bottom: 10px;">
    <el-form-item>
      <el-select v-model="query.permissionType" placeholder="请选择权限类型" clearable style="width: 180px;">
        <el-option label="请选择" :value="undefined" />
        <el-option v-for="t in permissionTypeOptions" :key="t.value" :label="t.label" :value="t.value" />
      </el-select>
    </el-form-item>
    <el-form-item style="width: 240px;">
      <el-select v-model="query.parentId" placeholder="请选择父级权限" clearable filterable>
        <el-option label="请选择" :value="undefined" />
        <el-option v-for="p in parentOptions" :key="p.id" :label="`${p.permissionName}（${p.permissionNo}）`" :value="p.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="GetPermission">查询</el-button>
      <el-button @click="Reset">重置</el-button>
    </el-form-item>
  </el-form>

  <el-form-item>
    <el-button type="success" @click="OpenAdd">新增</el-button>
  </el-form-item>

  <el-table :data="permissions" border style="width: 100%;height: 500px;">
    <el-table-column type="index" label="序号" width="60" />
    <el-table-column prop="permissionName" label="权限名称" />
    <el-table-column prop="permissionNo" label="权限编号" />
    <el-table-column prop="permissionType" label="类型" width="100">
      <template #default="scope">
        <el-tag :type="getTypeTag(scope.row.permissionType).type">{{ getTypeTag(scope.row.permissionType).text }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="permissionCode" label="权限编码" />
    <el-table-column prop="routePath" label="路由" />
    <el-table-column prop="componentPath" label="组件路径" />
    <el-table-column prop="sortOrder" label="排序" width="80" />
    <el-table-column prop="permissionStatus" label="状态" width="100">
      <template #default="scope">
        <el-tag :type="scope.row.permissionStatus ? 'success' : 'info'">{{ scope.row.permissionStatus ? '启用' : '禁用' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="" label="操作" >
        <template v-slot="scope">
            <el-button type="primary" link @click="OpenEdit(scope.row)">编辑</el-button>
            <el-button :type="scope.row.permissionStatus ? 'danger' : 'success'" link @click="ToggleEnable(scope.row)">{{ scope.row.permissionStatus ? '禁用' : '启用' }}</el-button>
            <el-button type="danger" link @click="DeletePermission(scope.row)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="addDialogVisible" :title="dialogTitle" width="640px">
    <el-form ref="addFormRef" :model="addForm" label-width="112px">
      <el-form-item label="权限名称" prop="permissionName">
        <el-input v-model="addForm.permissionName" placeholder="请输入权限名称" />
      </el-form-item>
      <el-form-item label="权限编号" prop="permissionNo">
        <el-input v-model="addForm.permissionNo" placeholder="请输入权限编号" />
      </el-form-item>
      <el-form-item label="权限类型" prop="permissionType">
        <el-select v-model="addForm.permissionType" placeholder="请选择权限类型" style="width: 100%">
          <el-option v-for="t in permissionTypeOptions" :key="t.value" :label="t.label" :value="t.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="父级权限" prop="parentId">
        <el-select v-model="addForm.parentId" placeholder="可不选（顶级）" style="width: 100%" clearable filterable>
          <el-option label="无（顶级）" :value="undefined" />
          <el-option v-for="p in parentOptions" :key="p.id" :label="`${p.permissionName}（${p.permissionNo}）`" :value="p.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="权限编码" prop="permissionCode">
        <el-input v-model="addForm.permissionCode" placeholder="请输入权限编码（按钮/功能建议必填）" />
      </el-form-item>
      <el-form-item label="路由路径" prop="routePath">
        <el-input v-model="addForm.routePath" placeholder="请输入路由路径（菜单/页面）" />
      </el-form-item>
      <el-form-item label="组件路径" prop="componentPath">
        <el-input v-model="addForm.componentPath" placeholder="请输入组件相对路径（如 views/System/Permission）" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addDialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="addSubmitting" @click="isEdit ? UpdatePermission() : AddPermission()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// @ts-ignore
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

const read = getReadClient(4)
const write = getWriteClient(4)

// 查询条件
const query: any = reactive({
  permissionType: undefined as undefined | number,
  parentId: undefined as undefined | number
})

// 权限列表
const permissions: any[] = reactive([] as any[])

// 下拉：权限类型（与后端为整型保持一致，展示友好文案）
const permissionTypeOptions = [
  { label: '目录', value: 1 },
  { label: '菜单', value: 2 },
  { label: '按钮', value: 3 }
]

const getTypeTag = (typeVal: number) => {
  const map: any = {
    1: { text: '目录', type: 'warning' },
    2: { text: '菜单', type: 'primary' },
    3: { text: '按钮', type: 'success' }
  }
  return map[typeVal] || { text: String(typeVal ?? ''), type: 'info' }
}

// 父级选项：直接复用已加载的权限列表（顶级/层级均可选择）
const parentOptions = computed(() => permissions)

// 新增相关
const addDialogVisible = ref(false)
const addSubmitting = ref(false)
const addFormRef = ref()
const dialogTitle = ref('新增权限')
const isEdit = ref(false)
const addForm: any = reactive({
  id: undefined as undefined | number,
  permissionNo: '',
  permissionName: '',
  permissionType: undefined as undefined | number,
  parentId: undefined as undefined | number,
  permissionCode: '',
  routePath: '',
  componentPath: '',
  sortOrder:''
})

const Reset = () => {
  query.permissionType = undefined
  query.parentId = undefined
}

const GetPermission = () => {
  read({
    url: 'sysread/api/Permission/GetPermission',
    method: 'get',
    params: {
      PermissionType: query.permissionType,
      ParentId: query.parentId
    }
  }).then((res: any) => {
    const list = res?.data?.data || []
    ;(permissions as any).splice(0, (permissions as any).length, ...list)
  }).catch(() => {
    ElMessage.error('查询失败')
  })
}

const OpenAdd = () => {
  isEdit.value = false
  dialogTitle.value = '新增权限'
  addForm.id = undefined
  addForm.permissionNo = ''
  addForm.permissionName = ''
  addForm.permissionType = undefined
  addForm.parentId = undefined
  addForm.permissionCode = ''
  addForm.routePath = ''
  addForm.componentPath = ''
  addDialogVisible.value = true
}

const OpenEdit = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '编辑权限'
  addForm.id = row.id
  addForm.permissionNo = row.permissionNo || ''
  addForm.permissionName = row.permissionName || ''
  addForm.permissionType = row.permissionType
  addForm.parentId = row.parentId
  addForm.permissionCode = row.permissionCode || ''
  addForm.routePath = row.routePath || ''
  addForm.componentPath = row.componentPath || ''
  addForm.sortOrder=row.sortOrder
  addDialogVisible.value = true
}

const AddPermission = () => {
  if (!addForm.permissionName) { return ElMessage.warning('请输入权限名称') }
  if (!addForm.permissionNo) { return ElMessage.warning('请输入权限编号') }
  if (!addForm.permissionType && addForm.permissionType !== 0) { return ElMessage.warning('请选择权限类型') }

  addSubmitting.value = true
  write({
    url: 'syswrite/api/Permission/AddPermission',
    method: 'post',
    data: addForm
  }).then((res: any) => {
    if (res?.data?.code === 200) {
      ElMessage.success(res.data.message || '新增成功')
      addDialogVisible.value = false
      GetPermission()
    } else {
      ElMessage.error(res?.data?.message || '新增失败')
    }
  }).finally(() => { addSubmitting.value = false })
}

const UpdatePermission = () => {
  if (!addForm.id) { return ElMessage.error('缺少权限ID') }
  if (!addForm.permissionName) { return ElMessage.warning('请输入权限名称') }
  if (!addForm.permissionNo) { return ElMessage.warning('请输入权限编号') }
  if (!addForm.permissionType && addForm.permissionType !== 0) { return ElMessage.warning('请选择权限类型') }

  addSubmitting.value = true
  write({
    url: 'syswrite/api/Permission/UpdatePermission',
    method: 'post',
    data: addForm
  }).then((res: any) => {
    if (res?.data?.code === 200) {
      ElMessage.success(res.data.message || '更新成功')
      addDialogVisible.value = false
      GetPermission()
    } else {
      ElMessage.error(res?.data?.message || '更新失败')
    }
  }).finally(() => { addSubmitting.value = false })
}

const DeletePermission = (row: any) => {
  ElMessageBox.confirm(`确定删除权限"${row.permissionName}"吗？`, '删除确认', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    write({
      url: 'syswrite/api/Permission/DeletePermission',
      method: 'post',
      params: { Id: row.id }
    }).then((res: any) => {
      if (res?.data?.code === 200) {
        ElMessage.success(res.data.message || '删除成功')
        GetPermission()
      } else {
        ElMessage.error(res?.data?.message || '删除失败')
      }
    })
  }).catch(() => {})
}

const ToggleEnable = (row: any) => {
  write({
    url: 'syswrite/api/Permission/EnablePermission',
    method: 'post',
    params: { Id: row.id }
  }).then((res: any) => {
    if (res?.data?.code === 200) {
      ElMessage.success(res.data.message || '操作成功')
      GetPermission()
    } else {
      ElMessage.error(res?.data?.message || '操作失败')
    }
  })
}

onMounted(() => {
  GetPermission()
})
</script>


